/*
* Copyright 2016 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-wechat-open-api
*
* @File name : ComponentWebPageAuthInterceptor.java
*
* @Author : LiuJun
*
* @Date : 2016年12月7日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2016年12月7日    LiuJun    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/
	
package com.yonyou.gmcc.gateway.wechat.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CookieConstant;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CookieSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yonyou.gmcc.gateway.wechat.service.interfaces.WechatApiServiceInterface;
import com.yonyou.gmcc.gateway.wechat.util.CookieUtil;


/**
*
* @author LiuJun
* 代公众号发起网页授权-拦截器
* @date 2016年12月7日
*/
public class ComponentWebPageAuthInterceptor implements HandlerInterceptor{
    
    private Logger logger=Logger.getLogger(ComponentWebPageAuthInterceptor.class);
    
    @Autowired
    private WechatApiServiceInterface wechatApiServiceInterface;
    

    
    
    //获取code
//    private static String AUTH_URL_GET_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE&component_appid=COMPONENT_APPID#wechat_redirect";

    /** 
    *
    * @author LiuJun
    * @date 2016年12月7日
    * @param request
    * @param response
    * @param handler
    * @return
    * @throws Exception
    * (non-Javadoc)
    * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        
//        String dealerCode = getCookiesByKey(request, CookieConstant.WECHAT_COOKIE_DEALERCODE);
//        String dealerAppId = getCookiesByKey(request, CookieConstant.WECHAT_COOKIE_DEALER_APPID);

        //code和appid
        String code  = request.getParameter("code");
        String appid  = request.getParameter("appid");
        logger.info("------receivecode:"+code+",url="+request.getRequestURL()+",uri="+request.getRequestURI());
        if(request.getRequestURI().contains("/error"))
        	return true;
        //微信积分商城，第三方接入调用该接口，不需要openid
        if(request.getRequestURI().contains("thirdport"))
        	return true;
        //测试token工具url
        if(request.getRequestURI().contains("parsetoken"))
        	return true;
        if(request.getRequestURI().contains("redirect"))
        	return true;
		//分享的页面不做openid校验
		if(request.getRequestURI().contains("sharepage") )
        	return true;
        if(request.getRequestURI().contains("drive") ){
            logger.info("进入试驾页面!");
            return true;}
        if(request.getRequestURI().contains("showroom") ){
            logger.info("进入车型展厅页面!");
            return true;}
        if(request.getRequestURI().contains("act") ){
            logger.info("进入资讯页面!");
            return true;}
		//-----------
		if(request.getRequestURI().contains("gmmcActivity/ActivityShare"))
        	return true;
		if(request.getRequestURI().contains("pointActivity"))
        	return true;
		//-----------------
		//url跳转预约详情的页面不做openid校验
//        if(request.getRequestURI().contains("/views/modules") )
//            return true;
//        //新的分享的页面不做openid校验
//        if(request.getRequestURI().contains("modules") )
//            return true;
        //会员的页面不做openid校验
        if(request.getRequestURI().contains("gmmc-wechat") )
            return true;
//        if(request.getRequestURI().contains("personredirect"))
//        	return true;
//        if(request.getRequestURI().contains("actredirect"))
//        	return true;
//        if(request.getRequestURI().contains("syredirect"))
//        	return true;
//        if(request.getRequestURI().contains("myActredirect"))
//        	return true;
//        if(request.getRequestURI().contains("servicehallredirect"))
//        	return true;
//        if(request.getRequestURI().contains("sendgiftredirect"))
//        	return true;
//        if(request.getRequestURI().contains("maintainbookredirect"))
//        	return true;
        //网关做认证页面，把认证信息写入cookie
        if(!CheckUtil.NullOrEmpty(code)){
        	writeWechatCookiesInfo(code,"",request,response);
            
        }else{ //业务请求没有经过zuul，而是在网关的controller转发，这时basecontroller中提供从cookie取身份的方法
        	String openId=CookieUtil.getOpenid(request);
        	if(CheckUtil.NullOrEmpty(openId)){
        		logger.info("拦截了cookie中没有openId的请求");
        		return false;
        	}
        	return true;
        }
        
        return true;
    }

    /**
    *
    * @author LiuJun
    * @date 2016年12月7日
    * @param request
    * @param response
    * @param handler
    * @param modelAndView
    * @throws Exception
    * (non-Javadoc)
    * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
    */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
    }

    /**
    *
    * @author LiuJun
    * @date 2016年12月7日
    * @param request
    * @param response
    * @param handler
    * @param ex
    * @throws Exception
    * (non-Javadoc)
    * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
    */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    public void writeWechatCookiesInfo(String code, String appid,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
    	logger.info("writeWechatCookiesInfo is entry,code=" + code + ";appid=" + appid);
    	try{
    		String openId = wechatApiServiceInterface.getOpenidByCode(code);
        	if(CheckUtil.NullOrEmpty(openId)) {
            	logger.info("gateway-wechat,openid is null="+openId);
        		return;
        	}
        	logger.info("gateway-wechat,openid="+openId);
        	//String authorizerAppid = getAuthorizerAppid(request);
        	//Long potentialUserId = getPotentialUserId(request);
        	//String dealerCode = getDealerCode(request);
        	if (!CheckUtil.NullOrEmpty(openId)) {
        		logger.info("--write cookie openid="+openId);
        		CookieUtil.writeOpenid(openId, response);
        	}
        	String userId = wechatApiServiceInterface.selectUserIdByOpenId(openId);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		logger.info("--write cookie userId="+userId);
        		Cookie cookies = new Cookie(CookieConstant.WECHAT_COOKIE_USERID,userId);
        		cookies.setMaxAge(6*60*60);//6小时有效期
                cookies.setPath("/");
                response.addCookie(cookies);
        	}
    	}catch(Exception e){
    		
    	}
    }    
}
